<template>
  <div class="main">
    <el-empty
    description="暂无申请单"
    v-if="list.length === 0"
    :image-size="200"></el-empty>
    <div class="table" v-if="list.length > 0">
      <el-table
        :stripe="true"
        :data="list"
        ref="dataList"
        @row-click="rowClick"
        max-height="550"
        style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-table
              :data="props.row.items"
              style="width: 100%">
              <el-table-column
                label="项目编号"
                prop="itemNo">
              </el-table-column>
              <el-table-column
                label="项目名称"
                prop="itemName">
              </el-table-column>
              <el-table-column
                label="检查部位"
                prop="checkPoint">
              </el-table-column>
              <el-table-column
                label="项目金额"
                prop="itemPrice">
              </el-table-column>
              <el-table-column
                label="缴费状态">
                <template slot-scope="props">
                  {{itemPayStateFormat(props.row.itemPayState)}}
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column
          label="申请单编号"
          width="150"
          prop="applyNo">
        </el-table-column>
        <el-table-column
          label="开单时间"
          width="190"
          prop="applyTime">
        </el-table-column>
        <el-table-column
          label="申请单名称"
          width="160"
          prop="itemTypeName">
        </el-table-column>
        <el-table-column
          label="开单医生"
          prop="applyDoctorName">
        </el-table-column>
        <el-table-column
          label="收费金额">
          <template slot-scope="props">
            {{sum(props.row.items)}}
          </template>
        </el-table-column>
        <el-table-column
          label="执行科室"
          prop="examDeptName">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="props">
            <el-button
              size="medium"
              type="primary"
              @click="check(props.row)">签到</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script lang="ts">
import { Component } from 'vue-property-decorator'
import { mixins } from 'vue-class-component'
import ReservationMixin from '@/mixins/reservation'
import { GetInspectionList, InspectionPayAndSign } from './apis/inspection'
import { IApplyInfoList, IPayAndSignQuery, IReservationInspection, IReservationInspectionItem, IReservationInspectionQuery } from './interface/inspection'

@Component
export default class InspectionList extends mixins(ReservationMixin) {
  private async created () {
    this.logger.info('打开申请单列表页')
    this.setTip('请选择申请单')
    this.setMaxTime(120)
    this.updateTimeHandler('home')
    if (this.store.state.InspectionList && this.store.state.InspectionList.length > 0) {
      this.list = this.store.state.InspectionList.filter(e => e.roomId === this.store.state.room?.HisId)
    } else {
      this.init()
    }
  }

  /**
   * 申请单列表
   */
  private list : IReservationInspection[] = []

  /**
   * 计算申请单总金额
   */
  private sum (items : IReservationInspectionItem[]): string {
    let sum = 0
    for (let i = 0; i < items.length; i++) {
      const element = items[i]
      sum = sum + parseFloat(element.itemPrice)
    }
    return this.ceil(sum, 2)
  }

  private ceil (number : number, fixed = 2) {
    if (!(fixed >= 0 && fixed <= 100)) {
      throw new RangeError('toCeil() digits argument must be between 0 and 100.')
    }
    let val = Math.ceil(number * Math.pow(10, fixed)) / Math.pow(10, fixed) + ''
    if (fixed > 0) {
      const intp = val.split('.')[0]
      const decp = val.split('.')[1] || ''
      if (decp.length < fixed) {
        val = intp + '.' + decp.padEnd(fixed, '0')
      }
    }
    return val
  }

  /**
   * 点击行展开详情
   */
  private rowClick (row: any) {
    for (let index = 0; index < this.list.length; index++) {
      const element = this.list[index]
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      this.$refs.dataList.toggleRowExpansion(element, false)
    }
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    this.$refs.dataList.toggleRowExpansion(row, true)
  }

  /**
   * 格式化缴费状态
   */
  private itemPayStateFormat (state : number) {
    switch (state) {
      case 0:
        return '未交费'
      case 1:
        return '已交费'
      case 2:
        return '作废'
      case 3:
        return '退费'
      default:
        return '未知'
    }
  }

  private async check (element: IReservationInspection) {
    if (this.store.state.InHosNo) {
      // 住院患者直接签到
      this.sign(element)
      return
    }
    const balance = this.store.state.patient?.Balance ?? 0
    const amount = parseFloat(this.sum(element.items)) - balance
    if (amount > 0 && element.payState === '0') {
      this.$messageBox.show({
        content: '储值卡余额不足, 是否充值?',
        confirmText: '充值',
        confirm: () => {
          this.clearTimeout()
          this.setMaxTime(0)
          this.store.state.AddCreditQuery = {
            Amount: parseFloat(this.ceil(amount, 2)),
            Use: '门诊充值',
            PatientId: this.store.state.patient?.ID ?? ''
          }
          this.$router.push(`/${this.getRoute()}/add-ercode`)
        },
        cancel: () => {
          this.sign(element)
        },
        cancelText: '直接签到'
      })
    } else {
      this.sign(element)
    }
  }

  private busy = false
  /**
   * 签到
   */
  private async sign (element: IReservationInspection) {
    try {
      if (this.busy) return
      this.busy = true
      this.showLoading('数据处理中...')
      this.logger.info('开始签到')
      if (!this.store.state.room || !this.store.state.room.HisId) {
        this.logger.warning('签到失败, 无效的诊室信息')
        this.$messageBox.show({ content: '无效的诊室信息' })
        return
      }
      if (!this.store.state.patient || !this.store.state.patient.CardNo) {
        this.logger.warning('签到失败, 无效的诊室信息')
        this.$messageBox.show({ content: '无效的诊室信息' })
        return
      }
      const query : IPayAndSignQuery = {
        RoomId: this.store.state.room.HisId,
        ApplyNo: element.applyNo
      }
      if (this.store.state.InHosNo) {
        query.InHosNo = this.store.state.patient.CardNo
      } else {
        query.CardNo = this.store.state.patient.CardNo
      }
      const result = await InspectionPayAndSign(query)
      this.hideLoading()
      this.busy = false
      if (result.data.Code === 200) {
        this.logger.info(`签到成功, 返回信息:${JSON.stringify(result.data)}`)
        this.$messageBox.show({
          content: '签到成功',
          confirm: () => {
            this.init()
            this.setMaxTime(60)
          },
          duration: 10,
          confirmText: '返回',
          cancelText: '退出',
          cancel: () => {
            this.home()
          }
        })
      } else {
        if (result.data.Message.indexOf('调用就诊卡支付失败') > -1) {
          this.logger.info(result.data.Message)
          const balance = this.store.state.patient.Balance ?? 0
          const amount = parseFloat(this.sum(element.items)) - balance
          if (amount > 0) {
            this.$messageBox.show({
              content: '储值卡余额不足, 是否充值?',
              confirmText: '充值',
              confirm: () => {
                this.clearTimeout()
                this.setMaxTime(0)
                this.store.state.AddCreditQuery = {
                  Amount: parseFloat(this.ceil(amount, 2)),
                  Use: '门诊充值',
                  PatientId: this.store.state.patient?.ID ?? ''
                }
                this.store.state.Inspection = element
                this.store.state.InspectionList = []
                this.$router.push(`/${this.getRoute()}/inspection-pay`)
              },
              cancel: () => {
                this.setTip('请选择申请单')
                this.setMaxTime(120)
                this.updateTimeHandler('home')
              }
            })
          } else {
            this.logger.warning(`签到失败, 返回信息:${JSON.stringify(result.data)}`)
            this.$messageBox.show({ content: result.data.Message.substring(0, 30) })
          }
        } else {
          this.logger.warning(`签到失败, 返回信息:${JSON.stringify(result.data)}`)
          this.$messageBox.show({ content: result.data.Message.substring(0, 30) })
        }
      }
    } catch (error) {
      this.$messageBox.show({ content: '签到失败, 请稍后重试' })
      this.logger.warning(`签到异常:${error}`)
    }
  }

  /**
   * 加载申请单列表
   */
  private async init () {
    try {
      this.logger.info('加载申请单列表')
      if (!this.store.state.room || !this.store.state.room.HisId) {
        this.logger.warning('加载申请单列表失败, 无效的诊室信息')
        this.$messageBox.show({ content: '无效的诊室信息' })
        return
      }
      const roomId = this.store.state.room.HisId
      const query : IReservationInspectionQuery = {
        RoomId: this.store.state.room.HisId
      }
      if (this.store.state.InHosNo) {
        query.InHosNo = this.store.state.patient?.CardNo
      } else {
        query.CardNo = this.store.state.patient?.CardNo
      }
      this.showLoading()
      const result = await GetInspectionList(query)
      setTimeout(() => {
        this.hideLoading()
      }, 300)
      if (result.data?.Code === 200) {
        const applyInfo : IApplyInfoList = JSON.parse(result.data.Data)
        this.list = applyInfo.applyInfoList.filter(e => e.roomId === roomId)
        console.log(result.data.Data, roomId)
        this.logger.info(`获取到申请单列表:${this.list}`)
        return
      }
      if (result.data?.Code === 1) {
        this.logger.warning(`获取申请单列表失败, 返回信息:${result.data.Message}`)
        this.$messageBox.show({ content: result.data.Message })
        return
      }
      this.logger.warning(`加载申请单列表失败, 返回信息:${result.data}`)
      this.$messageBox.show({ content: '获取申请单失败' })
    } catch (error) {
      this.logger.error(`加载申请单列表异常,${error}`)
      this.$messageBox.show({ content: '获取申请单失败' })
    }
  }
}
</script>
<style>
.el-table{
  font-size: 18px;
}
.el-button--medium{
  font-size: 18px;
}
</style>
<style scoped>
  .main {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    height: 100%;
    background: white;
    margin: 0 20px;
    box-shadow: 2px 2px 6px 0 rgba(0, 0, 0, 0.3);
    border-radius: 4px;
    padding: 20px 0;
  }
  .table{
    width:90%;
  }
</style>
